package bma.common.langutil.jdbc;


/**
 * 
 * @author guanzhong
 * @since 1.0 (imported from BMA.ESP Project)
 * 
 */
public class SQLUtil {

	public static boolean commonPatternToSQLPattern(String str,
			StringBuffer result) {
		boolean like = (str.indexOf('*') != -1 || str.indexOf('?') != -1);
		int c = str.length();
		for (int i = 0; i < c; i++) {
			char ch = str.charAt(i);
			if (ch == '*') {
				result.append('%');
			} else if (ch == '?') {
				result.append('_');
			} else if (ch == '%' && like) {
				result.append("\\%");
			} else if (ch == '_' && like) {
				result.append("\\_");
			} else {
				result.append(ch);
			}
		}
		return like;
	}

	public static void parseLikeString(String str, StringBuffer buf) {
		int c = str.length();
		for (int i = 0; i < c; i++) {
			char ch = str.charAt(i);
			if (ch == '%' || ch == '_' || ch == '\\') {
				buf.append('\\');
			}
			buf.append(ch);
		}
	}

	public static String toLikeString(String str) {
		if (str == null)
			return null;
		StringBuffer buf = new StringBuffer(str.length() + 10);
		buf.append('%');
		parseLikeString(str, buf);
		buf.append('%');
		return buf.toString();
	}

}
